package com.xc.common.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.util.ContentCachingRequestWrapper;

import com.ag.exception.CodeException;
import com.ag.utils.RequestUtils;
import com.alibaba.fastjson.JSON;
import com.xc.common.ResponseCode;
import com.xc.utils.Loggers;

public class ExceptionResolver implements HandlerExceptionResolver {
	private Object prettyString(String s) {
		try {
			return JSON.parse(s);
		} catch(Exception ex) {
		}
		
		return s;
	}
	
	public static CodeException getCodeException(Exception ex) {
		Throwable throwable = ex;
		
		while(throwable != null) {
			if(throwable instanceof CodeException) {
				return (CodeException) throwable;
			}
			
			throwable = throwable.getCause();
		}
		
		return null;
	}
	
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        Loggers.EXCEPTION.error("==============================ExceptionResolver=================================");
        
      //logger
  		Object p = null;
  		if("POST".equalsIgnoreCase(request.getMethod())) {//POST
  			if(request instanceof ContentCachingRequestWrapper) {
  				ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) request;
  				p = prettyString(new String(requestWrapper.getContentAsByteArray()));
  			} else {
  				p = RequestUtils.getPostParm(request);
  			}
  		} else {
  			p = JSON.toJSON(request.getParameterMap());
  		}
  		
      	
  		Throwable exception = getCodeException(ex);
  		if(exception == null) {
  			if(ex.getCause() != null) {
  				exception = ex.getCause();
  			} else {
  				exception = ex;
  			}
  		}
  		String message = String.format("请求地址:%s>>>%s<<<,参数:%s, 异常信息:%s,请求头:%s",  request.getRequestURI(), request.getMethod(), p, ex.toString(), JSON.toJSONString(RequestUtils.getRequestHeaders(request)));
//  		Loggers.EXCEPTION.error(message, exception);
  		Loggers.EXCEPTION.error("{} \r\n 异常堆栈: {}, 原始堆栈: {}" , message, ExceptionUtils.getStackTrace(exception), ExceptionUtils.getStackTrace(ex));
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("status", Integer.valueOf(ResponseCode.ERROR.getCode()));
		String msg;
		if (exception instanceof CodeException) {
			msg = ((CodeException) exception).getMsg();
		} else {
			msg = exception.getLocalizedMessage();
		}
        modelAndView.addObject("msg", msg);
//        modelAndView.addObject("data", ex.toString());

        return modelAndView;
    }
}
